package com.fedming.bottomnavigationdemo.Fragment;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.bg.BaseBackgroundFormat;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.format.bg.IBackgroundFormat;
import com.bin.david.form.data.format.grid.BaseGridFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.style.LineStyle;
import com.bin.david.form.data.table.TableData;
import com.bin.david.form.utils.DensityUtils;
import com.fedming.bottomnavigationdemo.Adapter.DoctorAdviceRecycleViewAdapter;
import com.fedming.bottomnavigationdemo.Bean.MedicationBean;
import com.fedming.bottomnavigationdemo.Bean.MedicationBeanAuto;
import com.fedming.bottomnavigationdemo.HomeActivity;
import com.fedming.bottomnavigationdemo.R;
import com.fedming.bottomnavigationdemo.Util.HttpUtils;

public class FeeQueryFragment extends BaseLazyFragment{
    private TextView dateDisplay;
    int mYear, mMonth, mDay;
    public List<MedicationBean> dataSource;
    public SmartTable table;
    TableData<MedicationBean> tableData;

    public TextView office2;
    public TextView admission_number2;
    public TextView name2;
    public TextView gender2;
    public TextView location_code2;
    public TextView admission_time2;
    public TextView nowTime;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fee_query_fragment,container,false);
        dateDisplay = (TextView) view.findViewById(R.id.pick_Date);
        office2 = (TextView) view.findViewById(R.id.office2);
        admission_number2 = (TextView) view.findViewById(R.id.admission_number2);
        name2 = (TextView) view.findViewById(R.id.name2);
        gender2 = (TextView) view.findViewById(R.id.gender2);
        location_code2 = (TextView) view.findViewById(R.id.location_code2);
        admission_time2 = (TextView) view.findViewById(R.id.admission_time2);
        nowTime = (TextView) view.findViewById(R.id.nowTime);
        table = view.findViewById(R.id.smartTable);
        table.setZoom(true);
        //setDataSource();
        dataSource = null;
        //获取当前日期
        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH)+1;
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        //将日期默认设置为当前日期

        StringBuffer stringBuffer;
        if(mMonth>10)
            stringBuffer = new StringBuffer().append(mYear).append("-").append(mMonth);
        else
            stringBuffer = new StringBuffer().append(mYear).append("-0").append(mMonth);
        if(mDay>10)
            stringBuffer.append("-").append(mDay).toString();
        else
            stringBuffer.append("-0").append(mDay).toString();
        String dateString = stringBuffer.toString();
        System.out.println("dateString:"+dateString);
        dateDisplay.setText(dateString);
        nowTime.setText(dateString);
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override  //用设置的时间来更新mYear等，然后重新显示时间
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        System.out.println("12111"+year+month+dayOfMonth);
                        mYear = year;
                        mMonth = month+1;
                        mDay = dayOfMonth;
                        StringBuffer stringBuffer;
                        if(mMonth>10)
                            stringBuffer = new StringBuffer().append(mYear).append("-").append(mMonth);
                        else
                            stringBuffer = new StringBuffer().append(mYear).append("-0").append(mMonth);
                        if(mDay>10)
                            stringBuffer.append("-").append(mDay).toString();
                        else
                            stringBuffer.append("-0").append(mDay).toString();
                        String dateString = stringBuffer.toString();
                        System.out.println("dateString:"+dateString);
                        displayDate(dateString);
                        displayDataByDate(dateString);
                    }
                },
                mYear, mMonth, mDay);

        dateDisplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog.show();//显示时间选择对话框
            }
        });

        mIsprepared = true;
        lazyLoad();
        Log.e(TAG,"onCreateView");
        return view;

    }
    @Override
    public void onStart() {
        super.onStart();
        InitData();
        UpdateFee();
    }
    public void displayDataByDate(String createDate) {
        List<MedicationBean> me = new ArrayList<>();
        for(MedicationBean medicationBean :HomeActivity.medicationBeans){
            System.out.println("create_time"+createDate);
            if(medicationBean.create_date.equals(createDate)){
                me.add(medicationBean);
            }
        }
        initTable(me);
    }
    public void InitData(){
        office2.setText(HomeActivity.office);
        admission_number2.setText(HomeActivity.pno);
        name2.setText(HomeActivity.name);
        String gender_string = "男";
            if(HomeActivity.gender =="f")
                gender_string = "女";
        gender2.setText(gender_string);
        location_code2.setText(HomeActivity.room+"-"+HomeActivity.code);
        admission_time2.setText(HomeActivity.admissionDate);

    }

    private void UpdateFee() {
        new Thread(new Runnable() {
            String body = null;
            @Override
            public void run() {
                try {
                    String url_server = "http://"+ HomeActivity.server_ip+":"+HomeActivity.info_port+"";//添加路径
                    String url = url_server+"/bed/cost"+"?patientId="+HomeActivity.patientId;
                    System.out.println(url);
                    body= HttpUtils.get(url).body().string();
                    System.out.println("返回的body:"+body);
                    Thread.sleep(2000);
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                System.out.println(body);
                if (body != null) {
                    if(JSON.parseObject(body).getJSONArray("data")!=null){
                        JSONArray data = JSON.parseObject(body).getJSONArray("data");
                        //List<MedicationBean> medicationBeans = new ArrayList<>();
                        HomeActivity.medicationBeans.clear();
                        for(Object obj:data){
                            MedicationBean medicationBean = new MedicationBean();
                            medicationBean.set(JSONObject.parseObject(obj.toString(), MedicationBeanAuto.class));
                            HomeActivity.medicationBeans.add(medicationBean);
                        }
                        if(HomeActivity.medicationBeans.size()>0){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    initTable(HomeActivity.medicationBeans);
                                }
                            });
                        }

                    }
//                    dataSource = new ArrayList<>();
//                    dataSource.add(new MedicationBean("100000", "5%葡萄糖sasaxxaxxasasasasasasasas","250ml" , "瓶", 2.56, 2, 5.12));
//                    dataSource.add(new MedicationBean("100000", "5%葡萄糖","250ml" , "瓶", 2.56, 2, 5.12));

                }
            }
        }).start();
    }

    //设置时间
    public void displayDate(String dateString) {
        nowTime.setText(dateString);
        dateDisplay.setText(dateString);

    }


    public FeeQueryFragment(){
        TAG = "FeeQueryFragment";
    }

    @Override
    protected void lazyLoad() {

    }

    private void initTable(List<MedicationBean> medicationBeans){
        //列标题
        Column<String> code = new Column<>("编码", "id");
        Column<String> medicationName = new Column<>("项目名称", "name");
        Column<String> size = new Column<>("规格", "format");
        Column<String> units = new Column<>("单位", "comment");
        Column<Double> price = new Column<>("单价", "price");
        Column<Integer> numbers = new Column<>("数量", "quantity");
        Column<Double> total_cost = new Column<>("金额", "total");
        Column<String> createTimes = new Column<>("创建时间", "create_date");
        total_cost.setAutoCount(true);
        tableData = new TableData<>("药品清单", medicationBeans, code, medicationName, size, units, price, numbers, total_cost, createTimes);
        table.setTableData(tableData);
        table.getConfig().setContentStyle(new FontStyle(15, Color.BLACK));//设置内容文字样式
        table.getConfig().setColumnTitleStyle(new FontStyle(15, Color.BLACK));//设置列标题文字样式
        table.getConfig().setShowXSequence(false); //设置是否显示顶部序号列
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setTableTitleStyle(new FontStyle(15, Color.BLACK));//设置表格标题文字样式
        table.getConfig().setYSequenceStyle(new FontStyle(15, R.color.浅蓝色));//设置左边序列文字样式
        //table.getConfig().setColumnTitleGridStyle()
        //table.getConfig().setMinTableWidth(5);

        //设置内容网格背景
        table.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {
            @Override
            public int getBackGroundColor(CellInfo cellInfo) {
                if(cellInfo.row %2 == 0) {
                    return ContextCompat.getColor(getContext(), R.color.content_bg);
                }
                return TableConfig.INVALID_COLOR;
            }
        });
        //设置左序列背景
        table.getConfig().setYSequenceCellBgFormat(new BaseCellBackgroundFormat<Integer>() {
            @Override
            public int getBackGroundColor(Integer position) {
                if(position%2 == 0){
                    return ContextCompat.getColor(getContext(),R.color.content_bg);
                }
                return TableConfig.INVALID_COLOR;

            }
        });

        table.getConfig().setColumnTitleBackground(new BaseBackgroundFormat(getResources().getColor(R.color.灰色)));


        //设置整个表格的最小宽度为屏幕的宽度
        WindowManager wm = getActivity().getWindowManager();
        int screenWith = wm.getDefaultDisplay().getWidth();
        table.getConfig().setMinTableWidth(screenWith);

        //设置网格列和行padding，这样就能够增大网络的尺寸了
//        table.getConfig().setHorizontalPadding(20);
//        table.getConfig().setVerticalPadding(30);
//        //增加列标题左右padding
//        table.getConfig().setColumnTitleVerticalPadding(30);
//        table.getConfig().setColumnTitleHorizontalPadding(20);


        //设置内容网格样式
        table.getConfig().setTableGridFormat(new BaseGridFormat(){
            @Override
            protected boolean isShowHorizontalLine(int col, int row, CellInfo cellInfo) {
                if(row == tableData.getLineSize() -1){
                    return false;
                }
                return true;
            }

            @Override
            protected boolean isShowVerticalLine(int col, int row, CellInfo cellInfo) {

                return false;

            }

            @Override
            protected boolean isShowColumnTitleVerticalLine(int col, Column column) {
                return false;
            }

            @Override
            protected boolean isShowColumnTitleHorizontalLine(int col, Column column) {
                return false;
            }
        });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHasLoadedOnce = false;
        mIsprepared = false;
        Log.e(TAG,"onDestroy");
    }
}
